﻿using System;
using System.Windows;
using System.Windows.Browser;
using System.Collections.Generic;
using System.Security.Cryptography;

using SBPweb.Forge.Cryptography;

namespace SBPweb.Forge.Controls.Silverlight.Utilities
{

    public static class InitialParametersHandler
    {

        public static IDictionary<string, string> DecryptParameters(IDictionary<string, string> parameters)
        {
            return DecryptParameters(parameters, null);
        }

        public static IDictionary<string, string> DecryptParameters(IDictionary<string, string> parameters, string additionalSalt)
        {
            string c = HtmlPage.Document.Cookies;
            string pt = string.Format("{0}#{1}", HtmlPage.Document.DocumentUri, HtmlPage.BrowserInformation.UserAgent);
            if (!string.IsNullOrEmpty(additionalSalt))
            {
                pt += additionalSalt;
            }
            CustomCryptographyProvider ccp = new CustomCryptographyProvider();
            try
            {
                string h = ccp.Decrypt<string>(parameters["hash"], pt);
                IDictionary<string, string> dict = new Dictionary<string, string>();
                foreach (string s in h.Split(','))
                {
                    string[] split = s.Split('=');
                    dict.Add(split[0], split[1]);
                }
                return dict;
            }
            catch (Exception ex)
            {
                throw new CryptographicException("Initial parameters could not be decrypted!", ex);
            }
        }

    }

}